package com.nowcoder.community.service;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.SensitiveFilter;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author AnYang
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/1/15
 */
@Service
public class DiscussPostService {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostService.class);

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    // caffeine核心接口：Cache，（排队等候）LoadingCache、（支持并发）AsyncLoadingCache

    // 帖子列表缓存
    private LoadingCache<String, List<DiscussPost>> postListCache;

    // 帖子总数缓存
    private LoadingCache<Integer, Integer> postRowsCache;

    // 不需要初始化多次
    @PostConstruct
    public void init() {
        // 初始化帖子列表缓存
        postListCache = Caffeine.newBuilder()
                // 最大数据量
                .maximumSize(maxSize)
                // 过期时间
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS) // 过期时间
                .build(// 缓存没有数据该怎么查，这个接口就是实现这个功能
                        new CacheLoader<String, List<DiscussPost>>() {
                            @Override
                            public @Nullable List<DiscussPost> load(@NonNull String key) throws Exception {
                                if (key == null || key.length() == 0) {
                                    throw new IllegalArgumentException("参数错误！");
                                }
                                String[] params = key.split(":");
                                if (params == null || params.length != 2) {
                                    throw new IllegalArgumentException("参数错误！");
                                }

                                int offset = Integer.parseInt(params[0]);
                                int limit = Integer.parseInt(params[1]);

                                // 二级缓存：Redis -> MySQL
                                logger.debug("load post list from DB.");
                                return discussPostMapper.selectDiscussPosts(0, offset, limit, 1);
                            }
                        });
        // 初始化帖子总数缓存
        postRowsCache = Caffeine.newBuilder()
                // 最大数据量
                .maximumSize(maxSize)
                // 过期时间
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS) // 过期时间
                .build(new CacheLoader<Integer, Integer>() {
                    @Override
                    public @Nullable Integer load(@NonNull Integer key) throws Exception {
                        logger.debug("load post rows from DB.");
                        return discussPostMapper.selectDiscussPostRows(key);
                    }
                });
    }

    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit, int orderMode) {
        // 缓存热门，缓存首页，缓存一页，一页数据由offset、limit决定
        if (userId == 0 && orderMode == 1) {
            return postListCache.get(offset + ":" + limit);
        }
        logger.debug("load post list from DB.");
        return discussPostMapper.selectDiscussPosts(userId, offset, limit, orderMode);
    }

    public int findDiscussPostRows(int userId) {
        // 查看自己的帖子时不走缓存
        if (userId == 0) {
            // 其实不需要key，和user没有关系
            return postRowsCache.get(userId);
        }
        logger.debug("load post rows from DB.");
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    public int insertDiscussPosts(DiscussPost post) {
        if (post == null) {
            throw new IllegalArgumentException("传递参数错误");
        }

        // 对post中的标题和内容进行过滤
        // 去除可能存在的html标签
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));
        // 对内容和标题进行过滤
        post.setTitle(sensitiveFilter.filter(post.getTitle()));
        post.setContent(sensitiveFilter.filter(post.getContent()));

        return discussPostMapper.insertDiscussPosts(post);
    }

    public DiscussPost findDiscussPostById(int id) {
        return discussPostMapper.selectDiscussPostById(id);
    }

    public int updateCommentCount(int id, int commentCount) {
        return discussPostMapper.updateCommentCount(id, commentCount);
    }

    public int updateType(int id, int type) {
        return discussPostMapper.updateType(id, type);
    }

    public int updateStatus(int id, int status) {
        return discussPostMapper.updateStatus(id, status);
    }

    public int updateScore(int id, double score) {
        return discussPostMapper.updateScore(id, score);
    }
}
